//
//  TweetTableViewCell.swift
//  Smashtag
//
//  Created by Gavin YANG on 3/11/15.
//  Copyright (c) 2015 HDIC. All rights reserved.
//

import UIKit

class TweetTableViewCell: UITableViewCell {
    var tweet: Tweet? {
        didSet {
            updateUI()
        }
    }
    
    @IBOutlet weak var tweetProfileImageView: UIImageView!
    @IBOutlet weak var tweetScreenNameLabel: UILabel!
    @IBOutlet weak var tweetTextLabel: UILabel!
    @IBOutlet weak var tweetCreatedLabel: UILabel!
    
    func updateUI() {
        // reset any existing tweet information
        tweetTextLabel?.attributedText = nil
        tweetScreenNameLabel?.attributedText = nil
        tweetProfileImageView?.image = nil
    //  tweetCreatedLabel?.text = nil
        
        // load new information from our tweet (if any)
        if let tweet = self.tweet {
            tweetTextLabel?.text = tweet.text
            if tweetTextLabel?.text != nil {
                for _ in tweet.media {
                    tweetTextLabel.text! += " 📷"
                }
            }
            
            tweetScreenNameLabel?.text = "\(tweet.user)" // tweet.user.description
            
            if let profileImageUrl = tweet.user.profileImageURL {
                let qos = Int(QOS_CLASS_USER_INITIATED.value)
                
                dispatch_async(dispatch_get_global_queue(qos, 0)) {
                    if let imageData = NSData(contentsOfURL: profileImageUrl) {
                        dispatch_async(dispatch_get_main_queue()) { () -> Void in
                            self.tweetProfileImageView?.image = UIImage(data: imageData)
                            
                            return
                        }
                    }
                }
            }
            
          let formatter = NSDateFormatter()
          if NSDate().timeIntervalSinceDate(tweet.created) > 24*60*60 {
              formatter.dateStyle = NSDateFormatterStyle.ShortStyle
          } else {
              formatter.timeStyle = NSDateFormatterStyle.ShortStyle
          }

          tweetCreatedLabel?.text = formatter.stringFromDate(tweet.created)
        }
    }
}
